import Cookies from 'js-cookie'
// cookie保存的天数
import config from '@/config'
import {forEach, hasOneOf, objEqual} from '@/libs/tools'

export const TOKEN_KEY = 'token'

import Utils from './mod.utils';
import String from './mod.string';
import Nim from './mod.nim';

let util = {};
util.title = function (title) {
  title = title || '魅力洪楼智慧街道';
  window.document.title = title;
}

// 请求后台地址
util.ajaxUrl = 'http://zhjd.jnaw.top/sd2';
// 富文本上传图片
util.DecoupledEditor_uploadUrl = 'http://zhjd.jnaw.top/sd2/file/addRichText';
// 下载app.apk地址
util.app_apk_url = 'http://sd.jnaw.top/apk/app.apk';


// 版本号
util.version = '0.4.22';

util.constant = {
  format: ['jpg', 'png', 'gif', 'jpeg', 'psd', 'bmp', 'JPG', 'PNG', 'GIF', 'JPEG', 'PSD', 'BMP'],
  // 志愿者能看到的功能
  VolunteerShowMenuListName: [
    'home_index',
    'ownspace_index',
    'chats_index',
    'addressBook_index',
    'my_group_index',
    'workStyle_index',
    'schedule_index',
    'logs_index',
    'knowledge_index',
    'affiche_index',
    'task_index',
    'approval_index',
  ],
  userMenuListName: [
    'chats_index',
    'addressBook_index',
    'my_group_index',
    'workStyle_index',
    'schedule_index',
    'logs_index',
    'knowledge_index',
    'affiche_index',
    'task_index',
    'approval_index',
    'clock_today',
    'collection',
    'meeting',
    'meeting_room',
    'user_list',
    'user_retired',
    'user_retirelPersonne',
    'user_retirelSetup',
    'user_checkIn',
    'user_frequency',
    'wechat_list',
    'community_index',
    'community_statistics',
    'socialRepo_index',
    'community_announcement_index',
    'ratepaying_index',
    'record_index',
    'contract_index',
    'assets_index',
    'my_assets',
    'my_repair',
    'city_index',
    'unsafe_punish_index',
    'feedback_index',
    'hotline_service_index',
    'dashboard_setup',
    'Timing_task_setup',
  ],
  AllMenuListName: [
    'chats_index',
    'addressBook_index',
    'my_group_index',
    'workStyle_index',
    'schedule_index',
    'logs_index',
    'knowledge_index',
    'affiche_index',
    'task_index',
    'approval_index',
    'clock_today',
    'collection',
    'meeting',
    'meeting_room',
    'user_list',
    'user_retired',
    'user_retirelPersonne',
    'user_retirelSetup',
    'user_checkIn',
    'user_frequency',
    'wechat_list',
    'community_index',
    'community_statistics',
    'socialRepo_index',
    'community_announcement_index',
    'ratepaying_index',
    'record_index',
    'contract_index',
    'assets_index',
    'my_assets',
    'my_repair',
    'city_index',
    'unsafe_punish_index',
    'feedback_index',
    'version_index',
    'access_time',
    'roles_index',
    'hotline_service_index',
    'dashboard_setup',
    'Timing_task_setup',
  ],
  officeappsUrl: 'https://view.officeapps.live.com/op/view.aspx?src=',//预览文件
  statistical_type: {
    chat: {
      id: 'chat_time',
      name: '消息',
    },
    task: {
      id: 'task_time',
      name: '任务',
    },
    journal: {
      id: 'journal_time',
      name: '日志',
    },
    schedule: {
      id: 'schedule_time',
      name: '日程',
    },
    knowledge: {
      id: 'knowledge_time',
      name: '知识库',
    },
    work_style: {
      id: 'work_style_time',
      name: '工作风采',
    },
    city: {
      id: 'city_time',
      name: '城市管理',
    },
    intell_lib: {
      id: 'social_repo_time',
      name: '社会智库',
    },
    regulate: {
      id: 'regulate_time',
      name: '安全整治',
    },
  },
  dashboard_person_all: [
    "apply", //申办
    "calendar", //日程
    "approval", //审批
    "knowledgeRepo", //知识库
    "taskList", //任务
    "task_delayed" //延期任务
  ],
  dashboard_person: [
    "apply", //申办
    "calendar", //日程
    "approval", //审批
    "knowledgeRepo", //知识库
  ],
  dashboard_department_all: [
    "schedule", //日程
    "published", //发表
    "task", //任务
    "task_delayed", //延期任务
    "apply", //申办
    "approval", //审批
    "knowledge", //知识库
    "checking_in" //考勤
  ],
  dashboard_department: [
    "apply", //申办
    "schedule", //日程
    "approval", //审批
    "knowledge", //知识库
  ],
  DrawerWidth: 800, // 抽屉的宽度
  WindowWidth: 1024, // 宽度
  WindowHeight: 768, // 高度
};

util.method = {
  post: 'POST',
  get: 'GET',
};

util.isAuthcData = {
  setInterval: null,
  count: 0,
};

util.ajax = function (context, params, isAuthcData) {
  var _this = this;
  if (context) {
    if (params) {
      if (params != null && params != '' && params != {}) {
        if (typeof params != 'object') {
          params = JSON.parse(params);
        }
        var domain = params.domain ? params.domain : _this.ajaxUrl;
        var url = params.url ? params.url : '';
        if (url == '') {
          console.log('Interface url is null');
          return false;
        }
        url = domain + url;
        var data = params.data ? params.data : {};
        var type = params.type ? params.type.toUpperCase() : 'GET';
        var successFuc = params.success ? params.success : null;
        var errorFuc = params.error ? params.error : null;

        if (!isAuthcData) {
          _this.isAuthcData.count = 0;
          if (_this.isAuthcData.setInterval) {
            clearInterval(_this.isAuthcData.setInterval); // 清除定时器
          }
          _this.isAuthcData.setInterval = setInterval(function () {
            _this.isAuthc(context, params);
          }, 1000 * 60 * 15);
        }

        const axiosAjax = require('axios');
        axiosAjax({
          method: type,
          url: url,
          params: type == 'POST' ? {} : data,
          data: data,
          responseType: 'json',
          withCredentials: true,
        }).then(function (response) {
          var res = response.data;
          if (!res) {// 无权限
            _this.loginOut(context);
            context.$Message.error('无权限,请重新登录!');
          } else if (res.result == 9) {// 无权限
            _this.loginOut(context);
            context.$Message.error('无权限,请重新登录!');
          } else if (res.result == 25) {// 登录超时
            _this.loginOut(context);
            context.$Message.error('登录超时,请重新登录!');
          } else {
            if (successFuc) {
              successFuc(res);
            }
          }
        }).catch(function (error) {
          console.log('ajax url:', url, data);
          console.log('ajax error:', error);
          if (errorFuc) {
            errorFuc(error);
          } else {
            var status = error.response.status || '';
            var message = error.message;
            context.$Message.error('错误码：' + status + '，' + message);
          }
          if (error.response) {
            console.log('code:', error.response.status);
          }
        })

      } else {
        console.log('Params is null!');
        return false;
      }
    } else {
      console.log('Params is undefined!');
      return false;
    }
  } else {
    console.log('VueComponent object is undefined!');
    return false;
  }
};
// 心跳
util.isAuthc = function (context, params) {
  var _this = this;
  _this.isAuthcData.count = _this.isAuthcData.count + 1;
  if (_this.isAuthcData.count >= 2) {
    _this.loginOut(context);
    context.$Message.error('登录超时,请重新登录!');
    if (_this.isAuthcData.setInterval) {
      clearInterval(_this.isAuthcData.setInterval); // 清除定时器
    }
    return false;
  }

  var data = {};
  var params = {
    url: '/user/isAuthc',
    type: _this.method.get,
    data: data,
    success: _successFun
  };
  _this.ajax(context, params, true);
  function _successFun(res) {
    if (res.result == 0) {

    } else {
      _this.$Message.error('失败!');
    }
  }
};

util.loginOut = function (context) {
  // 退出登录
  Nim.loginOutNimdata();
  // context.$store.commit('logout', context);
  // context.$store.commit('clearOpenedSubmenu');
  Cookies.set('token', '');
  context.$router.push({
    name: 'login'
  });
};
util.toStr = function (obj) {
  var res = '';
  if (typeof obj == 'string') {
    res = obj;
  } else if (typeof obj == 'object') {
    res = JSON.stringify(obj);
  }
  return res;
};

util.toJson = function (str) {
  var res = '';
  if (str != '' && str != undefined && str != null) {
    if (typeof str == 'string') {
      str = str.trim();
      res = JSON.parse(str) ? JSON.parse(str) : eval('(' + str + ')');
    } else if (typeof str == 'object') {
      res = str;
    }
  }
  return res;
};

// 记录用户查看页面的时间（秒）
util.statistical = function (context, type, seconds) {
  var _this = this;
  var context = context;
  if (context && type && seconds > 0) {
    var data = {};
    switch (type) {
      case 'chat_time' :
        data = {
          chat_time: seconds
        };
        break;
      case 'task_time' :
        data = {
          task_time: seconds
        };
        break;
      case 'journal_time' :
        data = {
          journal_time: seconds
        };
        break;
      case 'schedule_time' :
        data = {
          schedule_time: seconds
        };
        break;
      case 'knowledge_time' :
        data = {
          knowledge_time: seconds
        };
        break;
      case 'work_style_time' :
        data = {
          work_style_time: seconds
        };
        break;
      case 'city_time' :
        data = {
          city_time: seconds
        };
        break;
      case 'social_repo_time' :
        data = {
          social_repo_time: seconds
        };
        break;
      case 'regulate_time' :
        data = {
          regulate_time: seconds
        };
        break;
      default :
        break;
    }

    var params = {
      url: '/statistical-web/add',
      //domain: 'http://sd.jnaw.top/sd2-mock',
      type: _this.method.get,
      data: data,
      success: _successFun
    };
    _this.ajax(context, params);
    function _successFun(res) {
      if (res.result == 0) {
        console.log('保存成功', type, seconds);
      } else {
        console.log('保存失败', type, seconds, res);
      }
    }
  }
};

util.checkMobile = function (phone) {
  //正则：验证电话号码手机号码，包含至今所有号段
  var reg = /^(1[3|4|5|7|8])[\d]{9}$/;
  if (!reg.test(phone)) {//alert("电话号码格式错误!");obj.value="";obj.focus();
    return false;
  }
  else {//alert("您的电话号码:"+phone);
    return true;
  }
};

util.inOf = function (arr, targetArr) {
  let res = true;
  arr.forEach(item => {
    if (targetArr.indexOf(item) < 0) {
      res = false;
    }
  });
  return res;
};

util.openNewPage = function (context, routerName) {
  // 兼容老版本，新版本无需处理
};

export default util


export const setToken = (token) => {
  Cookies.set(TOKEN_KEY, token, {expires: config.cookieExpires || 1})
}

export const getToken = () => {
  const token = Cookies.get(TOKEN_KEY)
  if (token) return token
  else return false
}

export const hasChild = (item) => {
  return item.children && item.children.length !== 0
}

const showThisMenuEle = (item, access) => {
  if (item.meta && item.meta.access && item.meta.access.length) {
    if (hasOneOf(item.meta.access, access)) return true
    else return false
  } else return true
}
/**
 * @param {Array} list 通过路由列表得到菜单列表
 * @returns {Array}
 */
export const getMenuByRouter = (list, access) => {
  let res = []
  forEach(list, item => {
    if (!item.meta || (item.meta && !item.meta.hideInMenu)) {
      let obj = {
        icon: (item.meta && item.meta.icon) || '',
        name: item.name,
        meta: item.meta
      }
      if ((hasChild(item) || (item.meta && item.meta.showAlways)) && showThisMenuEle(item, access)) {
        obj.children = getMenuByRouter(item.children, access)
      }
      if (item.meta && item.meta.href) obj.href = item.meta.href
      if (showThisMenuEle(item, access)) res.push(obj)
    }
  })
  return res
}

/**
 * @param {Array} routeMetched 当前路由metched
 * @returns {Array}
 */
export const getBreadCrumbList = (routeMetched, homeRoute) => {
  let res = routeMetched.filter(item => {
    return item.meta === undefined || !item.meta.hide
  }).map(item => {
    let obj = {
      icon: (item.meta && item.meta.icon) || '',
      name: item.name,
      meta: item.meta
    }
    return obj
  })
  res = res.filter(item => {
    return !item.meta.hideInMenu
  })
  return [Object.assign(homeRoute, {to: homeRoute.path}), ...res]
}

export const showTitle = (item, vm) => vm.$config.useI18n ? vm.$t(item.name) : ((item.meta && item.meta.title) || item.name)

/**
 * @description 本地存储和获取标签导航列表
 */
export const setTagNavListInLocalstorage = list => {
  localStorage.tagNaveList = JSON.stringify(list)
}
/**
 * @returns {Array} 其中的每个元素只包含路由原信息中的name, path, meta三项
 */
export const getTagNavListFromLocalstorage = () => {
  const list = localStorage.tagNaveList
  return list ? JSON.parse(list) : []
}

/**
 * @param {Array} routers 路由列表数组
 * @description 用于找到路由列表中name为home的对象
 */
export const getHomeRoute = routers => {
  let i = -1
  let len = routers.length
  let homeRoute = {}
  while (++i < len) {
    let item = routers[i]
    if (item.children && item.children.length) {
      let res = getHomeRoute(item.children)
      if (res.name) return res
    } else {
      if (item.name === 'home') homeRoute = item
    }
  }
  return homeRoute
}

/**
 * @param {*} list 现有标签导航列表
 * @param {*} newRoute 新添加的路由原信息对象
 * @description 如果该newRoute已经存在则不再添加
 */
export const getNewTagList = (list, newRoute) => {
  const {name, path, meta} = newRoute
  let newList = [...list]
  if (newList.findIndex(item => item.name === name) >= 0) return newList
  else newList.push({name, path, meta})
  return newList
}

/**
 * @param {*} access 用户权限数组，如 ['super_admin', 'admin']
 * @param {*} route 路由列表
 */
const hasAccess = (access, route) => {
  if (route.meta && route.meta.access) return hasOneOf(access, route.meta.access)
  else return true
}

/**
 * 权鉴
 * @param {*} name 即将跳转的路由name
 * @param {*} access 用户权限数组
 * @param {*} routes 路由列表
 * @description 用户是否可跳转到该页
 */
export const canTurnTo = (name, access, routes) => {
  const routePermissionJudge = (list) => {
    return list.some(item => {
      if (item.children && item.children.length) {
        return routePermissionJudge(item.children)
      } else if (item.name === name) {
        return hasAccess(access, item)
      }
    })
  }

  return routePermissionJudge(routes)
}

/**
 * @param {String} url
 * @description 从URL中解析参数
 */
export const getParams = url => {
  const keyValueArr = url.split('?')[1].split('&')
  let paramObj = {}
  keyValueArr.forEach(item => {
    const keyValue = item.split('=')
    paramObj[keyValue[0]] = keyValue[1]
  })
  return paramObj
}

/**
 * @param {Array} list 标签列表
 * @param {String} name 当前关闭的标签的name
 */
export const getNextRoute = (list, route) => {
  let res = {}
  if (list.length === 2) {
    res = getHomeRoute(list)
  } else {
    const index = list.findIndex(item => routeEqual(item, route))
    if (index === list.length - 1) res = list[list.length - 2]
    else res = list[index + 1]
  }
  return res
}

/**
 * @param {Number} times 回调函数需要执行的次数
 * @param {Function} callback 回调函数
 */
export const doCustomTimes = (times, callback) => {
  let i = -1
  while (++i < times) {
    callback(i)
  }
}

/**
 * @param {Object} file 从上传组件得到的文件对象
 * @returns {Promise} resolve参数是解析后的二维数组
 * @description 从Csv文件中解析出表格，解析成二维数组
 */
export const getArrayFromFile = (file) => {
  let nameSplit = file.name.split('.')
  let format = nameSplit[nameSplit.length - 1]
  return new Promise((resolve, reject) => {
    let reader = new FileReader()
    reader.readAsText(file) // 以文本格式读取
    let arr = []
    reader.onload = function (evt) {
      let data = evt.target.result // 读到的数据
      let pasteData = data.trim()
      arr = pasteData.split((/[\n\u0085\u2028\u2029]|\r\n?/g)).map(row => {
        return row.split('\t')
      }).map(item => {
        return item[0].split(',')
      })
      if (format === 'csv') resolve(arr)
      else reject(new Error('[Format Error]:你上传的不是Csv文件'))
    }
  })
}

/**
 * @param {Array} array 表格数据二维数组
 * @returns {Object} { columns, tableData }
 * @description 从二维数组中获取表头和表格数据，将第一行作为表头，用于在iView的表格中展示数据
 */
export const getTableDataFromArray = (array) => {
  let columns = []
  let tableData = []
  if (array.length > 1) {
    let titles = array.shift()
    columns = titles.map(item => {
      return {
        title: item,
        key: item
      }
    })
    tableData = array.map(item => {
      let res = {}
      item.forEach((col, i) => {
        res[titles[i]] = col
      })
      return res
    })
  }
  return {
    columns,
    tableData
  }
}

export const findNodeUpper = (ele, tag) => {
  if (ele.parentNode) {
    if (ele.parentNode.tagName === tag.toUpperCase()) {
      return ele.parentNode
    } else {
      return findNodeUpper(ele.parentNode, tag)
    }
  }
}

export const findNodeDownward = (ele, tag) => {
  const tagName = tag.toUpperCase()
  if (ele.childNodes.length) {
    let i = -1
    let len = ele.childNodes.length
    while (++i < len) {
      let child = ele.childNodes[i]
      if (child.tagName === tagName) return child
      else return findNodeDownward(child, tag)
    }
  }
}

export const showByAccess = (access, canViewAccess) => {
  return hasOneOf(canViewAccess, access)
}

/**
 * @description 根据name/params/query判断两个路由对象是否相等
 * @param {*} route1 路由对象
 * @param {*} route2 路由对象
 */
export const routeEqual = (route1, route2) => {
  const params1 = route1.params || {}
  const params2 = route2.params || {}
  const query1 = route1.query || {}
  const query2 = route2.query || {}
  return (route1.name === route2.name) && objEqual(params1, params2) && objEqual(query1, query2)
}

/**
 * 判断打开的标签列表里是否已存在这个新添加的路由对象
 */
export const routeHasExist = (tagNavList, routeItem) => {
  let len = tagNavList.length
  let res = false
  doCustomTimes(len, (index) => {
    if (routeEqual(tagNavList[index], routeItem)) res = true
  })
  return res
}
